package engine.systems.spatial.spatial
{
	import engine.classes.enumerations.SystemPriority;
	import engine.systems.update.GameSystem;
	import engine.utils.MathUtils;
	
	import flash.display.DisplayObject;
	
	public class SpatialSystem extends GameSystem
	{
		public function SpatialSystem()
		{
			super(SpatialNode, updateNode, nodeAdded);
			
			this.priority = SystemPriority.SPATIAL;
		}
		
		private function updateNode(node:SpatialNode, time:Number):void
		{
			if(node.render.locked) return;
			
			var display:DisplayObject = node.render.display;
			
			var x:Number 		= node.spatial.x;
			var y:Number 		= node.spatial.y;
			var rotation:Number = node.spatial.rotation;
			var scaleX:Number	= node.spatial.scaleX;
			var scaleY:Number	= node.spatial.scaleY;
			
			if(node.offset)
			{
				x 			+= node.offset.x;
				y 			+= node.offset.y;
				rotation 	+= node.offset.rotation;
				scaleX 		+= node.offset.scaleX;
				scaleY 		+= node.offset.scaleY;
			}
			
			if(display.x != x) 				display.x 		= x;
			if(display.y != y) 				display.y 		= y;
			if(display.scaleX != scaleX) 	display.scaleX 	= scaleX;
			if(display.scaleY != scaleY)	display.scaleY 	= scaleY;
			
			rotation = MathUtils.toRotation(rotation);
			if(display.rotation != rotation) display.rotation = rotation;
		}
		
		private function nodeAdded(node:SpatialNode):void
		{
			if(node.spatial.sync)
			{
				node.spatial.x 			= node.render.display.x;
				node.spatial.y 			= node.render.display.y;
				node.spatial.rotation 	= node.render.display.rotation;
				node.spatial.scaleX 	= node.render.display.scaleX;
				node.spatial.scaleY 	= node.render.display.scaleY;
			}
		}
	}
}